# -*- coding: utf-8 -*-
import hashlib
import json

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    '5878': {  # 测试账号
        'API_KEY': '6BC37F83F158855FD9C81CE4CBC4CA04',
        'GATEWAY': 'http://111.230.195.206:81/?user_id={}&order_id={}&user_rmb={}&syn_url={}&pay_type={}&re_url={}&sign={}&ext_info={}',
        'QUERY_GATEWAY': 'http://111.230.195.206:81/query.asp?user_id={}&order_id={}&user_money={}&user_sign={}'
    },
    '1214': {  # 微信专用
        'API_KEY': '7C53918EC559651FD581A8DF8F2EEF06',
        'GATEWAY': 'http://111.230.192.24:81/?user_id={}&order_id={}&user_rmb={}&syn_url={}&pay_type={}&re_url={}&sign={}&ext_info={}',
        'QUERY_GATEWAY': 'http://111.230.192.24:81/query.asp?user_id={}&order_id={}&user_money={}&user_sign={}'
    },
    '8688': {  # 支付宝专用
        'API_KEY': '94DFAC00E61F8B3D44031DB5083A1862',
        'GATEWAY': 'http://123.207.239.247:81/?user_id={}&order_id={}&user_rmb={}&syn_url={}&pay_type={}&re_url={}&sign={}&ext_info={}',
        'QUERY_GATEWAY': 'http://123.207.239.247:81/query.asp?user_id={}&order_id={}&user_money={}&user_sign={}'
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_api_gateway(mch_id):
    return APP_CONF[mch_id]['GATEWAY']


def _get_api_query_gateway(mch_id):
    return APP_CONF[mch_id]['QUERY_GATEWAY']


def generate_charge_sign(parameter, key):
    '''  生成下单签名 '''
    s = 'user_id={}&order_id={}&user_rmb={}&syn_url={}&pay_type={}{}'.format(
        parameter['user_id'], parameter['order_id'], parameter['user_rmb'],
        parameter['syn_url'], parameter['pay_type'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    _LOGGER.info(u'origin string: %s, sign:%s', s, sign)
    return sign


def create_charge(pay, pay_amount, info):
    ''' 创建订单 '''
    charge_resp = {}
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    service = info.get('service')  # wechat or alipay
    if service == 'alipay':
        pay_type = 'alipay_wap'
    else:
        pay_type = 'weixin_wap'
    p_dict = {
        'user_id': app_id,
        'order_id': pay.id,
        'user_rmb': '%.2f' % pay_amount,
        'syn_url': '{}/pay/api/{}/xipay/'.format(
            settings.NOTIFY_PREFIX, settings.NOTIFY_PATH),
        're_url': '{}/pay/api/{}/xipay/{}/'.format(
            settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id),
        'pay_type': pay_type,
        'ext_info': '{}'
    }
    p_dict['sign'] = generate_charge_sign(p_dict, api_key)
    gateway = _get_api_gateway(app_id)
    gate_url = gateway.format(p_dict['user_id'], p_dict['order_id'], p_dict['user_rmb'],
                              p_dict['syn_url'], p_dict['pay_type'], p_dict['re_url'], p_dict['sign'],
                              p_dict['ext_info'])
    _LOGGER.info('xipay brefore data: %s', gate_url)
    charge_resp.update({
        'charge_info': gate_url
    })
    return charge_resp


def verify_notify_sign(parameter, key):
    '''验证通知签名 '''
    s = 'user_id={}&user_order={}&user_money={}&user_status={}&user_ext={}{}'.format(
        parameter['user_id'], parameter['user_order'], parameter['user_money'],
        parameter['user_status'], parameter['user_ext'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    _LOGGER.info(u'origin string: %s, sign:%s', s, sign)
    if sign != parameter['user_sign']:
        _LOGGER.info("xipay sign: %s, calculated sign: %",
                     parameter['user_sign'], sign)
        raise ParamError('sign not pass, data: %s' % parameter)
    return sign


def check_notify_sign(request):
    data = dict(request.GET.iteritems())
    _LOGGER.info("xipay notify data: %s", data)
    app_id = data['user_id']
    api_key = _get_api_key(app_id)
    verify_notify_sign(data, api_key)
    pay_id = data['user_order']
    if not pay_id:
        _LOGGER.error("fatal error, orderid not exists, data: %s" % data)
        raise ParamError('xipay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    trade_status = int(data['user_status'])
    mch_id = pay.mch_id
    trade_no = data['user_order']
    total_fee = float(data['user_money'])

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }

    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)

    if trade_status == 1:
        _LOGGER.info('xipay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    api_key = _get_api_key(app_id)
    user_money = '%.2f' % pay_order.total_fee
    s = 'user_id={}&user_order={}&user_money={}{}'.format(
        app_id, pay_order.id, user_money, api_key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    user_sign = m.hexdigest().upper()
    query_gateway = _get_api_query_gateway(app_id)
    gate_url = query_gateway.format(app_id, pay_order.id, user_money, user_sign)
    res = requests.get(gate_url).text
    print res
    res_obj = json.loads(res)
    trade_status, total_fee = res_obj['Order_status'], res_obj['real_rmb']
    trade_no = pay_order.id
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    if trade_status == 'code_1':
        _LOGGER.info('xipay query order success, mch_id:%s pay_id:%s',
                     pay_order.mch_id, pay_order.id)
        res = order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                       total_fee, trade_no, extend)
        if res:
            # async notify
            async_job.notify_mch(pay_order.id)
